<template>
  <div>
    <div class="detail_box">
      <div class="operate_box">
        <div class="item_box">
          <div class="operate_item">
            <label>关键词：</label>
            <el-input type="text" clearable placeholder="请输入关键词" v-model="keyword"></el-input>
          </div>

          <div class="operate_item">
            <label>用户：</label>
            <el-select
              filterable
              clearable
              v-model="roleId"
              placeholder="请选择用户">
              <el-option
                v-for="(item,index) in roles"
                :key="index"
                :label="item.name"
                :value="item.type">
              </el-option>
            </el-select>
          </div>

          <div class="operate_item">
            <span class="operate_btn search_btn" @click="getTableInfo(1)">查询</span>
            <span class="operate_btn reset_btn" @click="resetTable">重置</span>
          </div>
        </div>
        <div class="btn_box" v-if="btn&&btn.add">
          <span class="operate_btn search_btn" @click="openPopup('')">新增</span>
        </div>
      </div>
      <div class="table_box">
        <el-table
          border
          v-loading="loading"
          :header-cell-style="tableHeader"
          ref="multipleTable"
          :data="tableInfo"
          tooltip-effect="dark"
          style="width: 100%;">
          <el-table-column
            width="120"
            prop="id"
            label="ID">
          </el-table-column>
          <el-table-column
            sortable
            prop="modifyTime"
            label="修改时间">
            <template slot-scope="scope">
              <p style="text-align: left">{{ formatTime(scope.row.modifyTime) }}</p>
            </template>
          </el-table-column>
          <el-table-column
            prop="username"
            label="账号">
          </el-table-column>
          <el-table-column
            label="姓名">
            <template slot-scope="scope">
              <p style="text-align: left">{{ scope.row.name?scope.row.name:'——' }}</p>
            </template>
          </el-table-column>
          <el-table-column
            prop="typeName"
            label="用户类型">
          </el-table-column>
          <el-table-column
            width="160"
            label="头像">
            <template slot-scope="scope">
              <img v-if="scope.row.photoUrl" :src="scope.row.photoUrl" class="icon"
                   @click="openImg(scope.row.photoUrl)">
              <span v-else>——</span>
            </template>
          </el-table-column>
          <el-table-column
            width="100"
            label="状态" v-if="!(btn.freeze||btn.unfreeze)">
            <template slot-scope="scope">
                    <span class="normal"
                          :class="{'unusual':scope.row.enable===0}">{{ scope.row.enable ? '可用' : '冻结' }}</span>
            </template>
          </el-table-column>

          <el-table-column
            label="状态"
            prop="2"
            sortable="custom"
            width="100" v-if="btn.freeze||btn.unfreeze">
            <template slot-scope="scope">
              <div>
                <el-switch
                  :active-value="1"
                  :inactive-value="0"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  @change="deleteItem(scope.row,scope.$index)"
                  v-model="scope.row.enable">
                </el-switch>
                <span class="normal" v-if="scope.row.enable===1">可用</span>
                <span class="unusual" v-else>冻结</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column
            label="操作"
            v-if="btn&&(btn.update||btn.bind || btn.delete || btn.removeBind)"
            fixed="right"
            width="240">
            <template slot-scope="scope">
              <div class="table_btn">
                <span class="change_info" @click="openPopup(scope.row)" v-if="btn.update">编辑</span>
                <span class="change_info" @click="createCode(scope.row,2)" v-if="btn.bind&&!scope.row.wxOpenId&&(scope.row.type===1||scope.row.type===3||scope.row.type===4||scope.row.type===5||scope.row.type===6)">绑定微信</span>
                <span class="change_info delete_btn" @click="removeBind(scope.row)" v-if="btn.removeBind&&scope.row.wxOpenId&&(scope.row.type===1||scope.row.type===3||scope.row.type===4||scope.row.type===5||scope.row.type===6)">解除绑定</span>
                <span class="change_info" @click="createCode(scope.row,1)" v-if="btn.bind&&scope.row.type===5">绑定客户</span>
                <span class="change_info delete_btn" @click="deleteUser(scope.row)" v-if="btn.delete">删除</span>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="record_page">
        <span class="page_count">共<i>{{ totals }}</i>条</span>
        <el-pagination
          @size-change="sizeChange"
          @current-change="getTableInfo"
          background
          :current-page="currentPage"
          :page-sizes="[15, 20, 30, 40]"
          :page-size="pageSize"
          layout="prev, pager, next, sizes,jumper"
          :total="totals">
        </el-pagination>
      </div>
    </div>
    <Edit v-if="isPop" :uid="userId" @listenToChild="listenToEdit"></Edit>
    <ShowImg :icon="icon" @listenToChildEvent="getOpen" v-if="isOpen"></ShowImg>
    <qrcode :qrcode="qrcode" v-if="isBind"  @listenToChild="listenToEdit"></qrcode>
  </div>
</template>

<script>
import commons from "@/utils/common";
import {restUrl} from '../../../../url.js'
import ShowImg from "../../../components/ShowImg";
import Edit from './edit'
import qrcode from "./qrcode";
import {getBtn} from "@/utils/btnAuth";
import {delData, deleteUser, listData, unbindApplet} from "@/api/sys/user";
import {getSelect} from "@/api/sys/role";
import axios from 'axios'
import {getToken} from "@/utils/auth";

export default {
  components: {
    Edit,
    ShowImg,
    qrcode
  },
  data() {
    return {
      param: {folder: 'web/user'},
      uploadUrl: restUrl + '/common/upload',
      firstMenu: '',
      keyword: '',
      tableInfo: [],
      currentPage: 1,
      pageSize: 15,
      totals: 1,
      loading: false,
      isPop: false,
      userId: '',
      isBind: false,
      qrcode: '',
      title:'',
      isOpen: false,
      icon: '',
      roles:[],
      roleId:'',
      btn:{},
    }
  },
  mounted() {
    this.getRoles();
    this.btn = getBtn();
    if (this.btn.query) {
      this.getTableInfo(1);
    }
  },
  methods: {
    getTableInfo(page) {
      let that = this;
      that.loading = true;
      that.currentPage = page;
      let queryParams = {
        limit:that.pageSize,
        page:page,
        keyword:that.keyword,
        type:that.roleId
      }
      listData(queryParams).then(res => {
        that.tableInfo = res?res.list:[];
        that.totals = res?res.count:0;
        that.loading = false;
      }).catch((e) => {
        that.loading = false;
      });
    },


    resetTable() {
      this.keyword = '';
      this.pageSize = 15;
      this.roleId = '';
      this.getTableInfo(1)
    },

    getRoles(){
      getSelect().then(res => {
        this.roles = res?res:[];
      });
    },

    // 打开弹窗
    openPopup(obj) {
      this.isPop = true;
      this.userId = obj ? obj.id : '';
      this.title = obj ? obj.username : '';
    },

    listenToEdit(e) {
      this.isPop = false;
      this.isBind = false;
      if (e.refresh) {
        this.getTableInfo(this.currentPage)
      }
    },

    createCode(obj,type){
      let that = this;
      let token = getToken();
      if (token) {
        that.loading = true;
        axios.defaults.headers.common['token'] = token
        axios.get(restUrl + '/sys/user/createUserQRCode?state=' + type + '&userId=' + obj.id, {responseType: "arraybuffer"}).then(res => {
          if (res.status === 200) {
            return 'data:image/png;base64,' + btoa(new Uint8Array(res.data).reduce((data, byte) => data + String.fromCharCode(byte), ''));
          }
        }).then(function (data) {
          //接收转换后的Base64图片
          that.loading = false;
          // 设置图片地址
          that.qrcode = data;
          that.isBind = true;
        })
      }
    },

    // 解除绑定
    removeBind(obj){
      let that = this;
      that.$confirm('确定解除'+obj.username+'的微信账号?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let param = {userId:obj.id}
        return unbindApplet(param);
      }).then(() => {
        that.getTableInfo(that.currentPage);
        that.$message.success({
          message:'解绑成功！',
          duration:1500
        });
      }).catch(() => {
        // console.product('fail')
      });
    },

    deleteUser(obj) {
      let that = this;
      that.$confirm(`确认删除${obj.name}用户？`, '提示', {
        confirmButtonText: "确定",
        cancelButtonText: '取消',
        type: 'danger'
      }).then(() => {
        deleteUser(obj.id).then((res)=> {
          that.getTableInfo(that.currentPage);
          that.$message.success({
            message:'删除成功！',
            duration:1500
          });
        })
      })
        // .then(() => {
        // that.getTableInfo(that.currentPage);
        // that.$message.success({
        //   message:'删除成功！',
        //   duration:1500
        // });
      // })

    },

    // 冻结
    deleteItem(obj,index) {
      let that = this;
      that.$confirm('确定'+(obj.enable===0?'冻结':'解冻')+obj.username+'账号?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let param = {id:obj.id,enable:obj.enable}
        return delData(param);
      }).then(() => {
        that.getTableInfo(that.currentPage);
        that.$message.success({
          message:'修改成功！',
          duration:1500
        });
      }).catch(() => {
        //重置
        that.tableInfo[index].enable = obj.enable == 0 ? 1:0;
      });
    },

    sizeChange(val) {
      this.pageSize = val;
      this.getTableInfo(1)
    },

    formatTime(time) {
      return commons.formatTime(time)
    },

    openImg(url) {
      this.isOpen = true;
      this.icon = url;
    },

    getOpen(e) {
      this.isOpen = e;
    },
    // 设置table标题居中
    tableHeader({row, column, rowIndex, columnIndex}) {
      return 'background:#F0F2F5;color:#111;padding:10px 0;font-size:14px;font-weight:600'
    },
  }
}
</script>

<style scoped>
.check_btn{
  color: #f7ab20;
}
</style>
